package com.xinchen.all.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.text.TextUtils
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContract
import com.maple.base.base.BaseActivity
import com.maple.utils.util.LogUtils
import com.xinchen.all.R

class Bluetooth2Activity : BaseActivity() {

    private var tvStatus: TextView? = null

    private var bluetoothAdapter: BluetoothAdapter? = null
    private var bluetoothLeScanner : BluetoothLeScanner? = null
    override fun getLayoutId(): Int = R.layout.activity_bluetooth2

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        tvStatus = findViewById(R.id.tv_status)
    }

//    private val handle: WeakHandler by lazy {
//        WeakHandler(Looper.myLooper(),object : Handler.Callback{
//            override fun handleMessage(message: Message): Boolean {
////                when(message.what) {
////
////                }
//                LogUtils.logGGQ("=====${message.what}")
//                return true
//            }
//        })
//    }
private val handler : Handler = object : Handler(){

    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        LogUtils.logGGQ("=======${msg.what}")
        when(msg.what) {

        }
    }
}

    override fun initData(savedInstanceState: Bundle?) {
        checkBluetooth()
    }


    private fun checkBluetooth() {
        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast("设备不支持蓝牙")
            return
        }
        val bluetoothManager: BluetoothManager? = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?
        bluetoothAdapter = bluetoothManager?.adapter
        if(bluetoothAdapter == null) {
            showToast("设备不支持蓝牙")
            return
        }
        bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner
        enabledBluetoothAndLocation()
    }


    private fun enabledBluetoothAndLocation() {
        // 开启蓝牙
        if(!(bluetoothAdapter!!.isEnabled)){
            //不建议强制打开蓝牙，官方建议通过Intent让用户选择打开蓝牙
//            bluetoothAdapter.enable()
            launcherBluetoothResult.launch(Unit)
            return
        }
        // 开启位置服务，
        // 支持获取ble蓝牙扫描结果
        if (!isLocationOpen(applicationContext)) {
            launcherLocationResult.launch(Unit)
            return
        }

        onScanBluetoothDevices()

    }



    private val launcherBluetoothResult = registerForActivityResult(object :
        ActivityResultContract<Unit, Boolean>() {
        override fun createIntent(context: Context, input: Unit): Intent {
            return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        }

        override fun parseResult(resultCode: Int, intent: Intent?): Boolean {
            return resultCode == Activity.RESULT_OK
        }
    }) {
        if(it != null && it) {
            showToast("已开启蓝牙")
            enabledBluetoothAndLocation()
        }
    }


    private val launcherLocationResult = registerForActivityResult(object :
        ActivityResultContract<Unit, Boolean>() {
        override fun createIntent(context: Context, input: Unit): Intent {
            return Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
        }

        override fun parseResult(resultCode: Int, intent: Intent?): Boolean {
            return resultCode == Activity.RESULT_OK
        }
    }) {
        if(it != null && it) {
            showToast("已开启位置服务")
            enabledBluetoothAndLocation()
        }
    }

    private fun isLocationOpen(context: Context): Boolean {
        if(Build.VERSION.SDK_INT <  Build.VERSION_CODES.M) return true
        val locationManager: LocationManager? = context.getSystemService(LOCATION_SERVICE) as LocationManager?
        //gps定位
        val isGpsProvider: Boolean = locationManager?.isProviderEnabled(LocationManager.GPS_PROVIDER)?: false
        LogUtils.logGGQ("=isGpsProvider=>${isGpsProvider}")
        //网络定位
        val isNetWorkProvider: Boolean = locationManager?.isProviderEnabled(LocationManager.NETWORK_PROVIDER)?: false
        LogUtils.logGGQ("=isNetWorkProvider=>${isNetWorkProvider}")

        return isGpsProvider || isNetWorkProvider
    }


    private fun onScanBluetoothDevices() {
        if(bluetoothLeScanner == null) {
            showToast("未获取到蓝牙扫描对象")
            return
        }
        LogUtils.logGGQ("开始扫描蓝牙===》")

        scan2()
    }

    @SuppressLint("MissingPermission")
    private fun scan2() {
        if(com.huyuhui.fastble.BleManager.isScanning()) {
            com.huyuhui.fastble.BleManager.cancelScan()
        }

        com.huyuhui.fastble.BleManager.scan(object : com.huyuhui.fastble.callback.BleScanCallback {
            override fun onLeScan(
                oldDevice: com.huyuhui.fastble.data.BleDevice,
                newDevice: com.huyuhui.fastble.data.BleDevice,
                scannedBefore: Boolean
            ) {
                if(!scannedBefore) {
                    if(TextUtils.equals("20:23:12:11:01:67",newDevice.mac)) {
                    }
                }
            }

            override fun onScanFinished(scanResultList: List<com.huyuhui.fastble.data.BleDevice>) {

            }

            override fun onScanStarted(success: Boolean) {

            }
            override fun onFilter(bleDevice: com.huyuhui.fastble.data.BleDevice): Boolean {
                if(TextUtils.isEmpty(bleDevice.name)) return false
                return true
            }
        })
    }
}